<?php

namespace App\Http\Controllers\admin\service;

use App\Http\Controllers\utils\ToolUtil;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\utils\LogUtil;
use Maatwebsite\Excel\Facades\Excel;
use PHPExcel_Reader_Excel2007;

class WhiteAppService
{


    public static function handleWhiteApp($param){
        set_time_limit(0);
        $phpReader = new PHPExcel_Reader_Excel2007();
        $phpExcel = $phpReader->load($param['file']); //获取文件
        $currentSheet =$phpExcel->getSheet(0); //获取文件第一个表单
        $allColumn = $currentSheet->getHighestColumn(); //获取最大列号
        $allRow = $currentSheet->getHighestRow();//获取总行数
        $maxColumnNumber = \PHPExcel_Cell::columnIndexFromString($allColumn);//获取总列数
        if($maxColumnNumber!=1){
            return ToolUtil::returnJson(301,'格式有问题');
        }
        $data = [];
        for($currentRow =2;$currentRow<=$allRow;$currentRow++){
            //获取excel列数信息
            for ($currentColumn=0;$currentColumn<$maxColumnNumber;$currentColumn++){
                $data[$currentRow] = trim($currentSheet->getCellByColumnAndRow($currentColumn,$currentRow)->getValue());
            }
        }
        return implode(',',$data);
    }

    /**
     * 增加应用白名单信息
     * @param $param
     * @return false|string
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     */
    public static function whiteAppAdd($param){

        if($param['type']==1){
            if(empty($param['package'])){
                return ToolUtil::returnJson(401,'包名信息不存在');
            }
            $val = $param['package'];
        }elseif($param['type']==2){
            if(empty($param['file'])){
                return ToolUtil::returnJson(401,'请上传文件');
            }
            
            if(!is_object($param['file'])){
                return ToolUtil::returnJson(401,'文件为空');
            }
            $fileName = $param['file']->getClientOriginalName();
            
            $suffix = explode('.',$fileName);
            $type = ['xlsx','xls'];
            if(!in_array($suffix[count($suffix)-1],$type)){
                return ToolUtil::returnJson(302,'文件类型必须为xlsx或xls');
            }
            $val = self::handleWhiteApp($param);
        }else{
            return ToolUtil::returnJson(301,'类型有误');
        }
        if(empty($val)){
            return ToolUtil::returnJson(401,'包名为空');
        }

        $batch_id = '';
        $sn = '';
        $group = (int)$param['group'];
        if($group === 3){

            if(empty($param['batch'])){
                return ToolUtil::returnJson(300,'批次不能为空');
            }
            $batch_id = $param['batch'];
            $pushArr = explode(',',$param['batch']);
            foreach ($pushArr as $key => $value) {
                if(DB::table('t_white_app')->whereRaw(" find_in_set('{$value}',batch_id) ")->value('id')){
                    return ToolUtil::returnJson(301,'存在该批次信息');
                }
            }
            $push_param['type'] = 1;

        }else if($group === 4){

            if(empty($param['sn'])){
                return ToolUtil::returnJson(300,'sn不能为空');
            }
            $sn = ToolUtil::filterStr($param['sn']);
            if(DB::table('t_white_app')->where('sn',$sn)->value('id')){
                return ToolUtil::returnJson(301,'存在该批次信息');
            }
            $push_param['type'] = 2;
            $pushArr = array($sn);

        }else{
            return ToolUtil::returnJson(401,'group错误');
        }

        try{

            $logArr['userId'] = (int)$param['userId'];
            $logArr['remark'] = '增加应用白名单';

            $push_param['statusType'] = '增加应用白名单';
            $push_param['title'] = 'OK';
            $push_param['batch'] = $pushArr;
            $push_param['status'] = 1;
            $push_param['contentType'] = 46;
            $push_param['userId'] = (int)$param['userId'];
            $push_data = ['package_name'=>$val];
            $jPush = LogUtil::addPushLog($push_param,$push_data);

            if(in_array(200,$jPush)){

                $data = [
                    'admin_id'=>$param['userId'],
                    'package_name'=>$val,
                    'batch_id'=>$batch_id,
                    'sn'=>$sn,
                    'group'=>$group,
                    'create_time'=>time()
                ];

                if(DB::table('t_white_app')->insert($data)){
                    $logArr['details'] = '成功';
                    LogUtil::addAdminLog($logArr);
                    return ToolUtil::returnJson(200,'成功');
                }else{
                    $logArr['details'] = '失败';
                    LogUtil::addAdminLog($logArr);                    
                    return ToolUtil::returnJson(300,'失败');
                }
            }else{
                $logArr['details'] = '推送失败';
                LogUtil::addAdminLog($logArr);                
                return ToolUtil::returnJson(300,'推送失败，具体原因请查看管控操作日志');
            }

        }catch (\Exception $exception){
            return ToolUtil::returnJson(500,$exception->getMessage());
        }        

    }


    /**
     * 修改应用白名单设置
     * @param $param
     * @return false|string
     */
    public static function whiteAppEdit($param){

        if($param['type']==1){
            if(empty($param['package'])){
                return ToolUtil::returnJson(401,'包名信息不存在');
            }
            $val = $param['package'];
        }elseif($param['type']==2){
            if(empty($param['file'])){
                return ToolUtil::returnJson(401,'请上传文件');
            }
            if(!is_object($param['file'])){
                return ToolUtil::returnJson(401,'文件为空');
            }
            $fileName = $param['file']->getClientOriginalName();
            $suffix = explode('.',$fileName);
            $type = ['xlsx','xls'];
            if(!in_array($suffix[count($suffix)-1],$type)){
                return ToolUtil::returnJson(302,'文件类型必须为xlsx或xls');
            }
            $val = self::handleWhiteApp($param);
        }else{
            return ToolUtil::returnJson(301,'类型有误');
        }
        if(empty($val)){
            return ToolUtil::returnJson(401,'包名为空');
        }

        $white_app = DB::table('t_white_app')->where('id',$param['id'])->first(['batch_id','package_name','admin_id','sn','group']);
        if(empty($white_app)){
            return ToolUtil::returnJson(301,'不存在该信息');
        }
        if(!ToolUtil::isPower($param['userId'],$white_app['admin_id'])){
            return ToolUtil::returnJson(300,'没有权限');
        }

        $batch_id = '';
        $sn = '';

        if($white_app['group'] === 4){
            if(empty($param['sn'])){
                return ToolUtil::returnJson(300,'sn不能为空');
            }
            $sn = $param['sn'];
            $push_param['type'] = 2;
            $pushArr = array($white_app['sn']);

        }else{
            if(empty($param['batch'])){
                return ToolUtil::returnJson(300,'批次不能为空');
            }
            $batch_id = $param['batch'];
            $push_param['type'] = 1;
            $pushArr = explode(',',$param['batch']);
            foreach ($pushArr as $key => $value) {
                $id = DB::table('t_white_app')->whereRaw(" find_in_set('{$value}',batch_id) ")->value('id');
                if($id && $id != $param['id']){
                    return ToolUtil::returnJson(301,'存在相同组别');
                }
            }

            $batchArr2 = explode(',',$white_app['batch_id']);
            $batchArr3 = array_diff($batchArr2,$pushArr);

            if(!empty($batchArr3)){

                $push_param['statusType'] = '编辑应用白名单';
                $push_param['title'] = 'OK';
                $push_param['batch'] = $batchArr3;
                $push_param['status'] = 1;
                $push_param['contentType'] = 46;
                $push_param['type'] = 1;
                $push_param['userId'] = (int)$param['userId'];
                $push_data = ['package_name'=>''];
                LogUtil::addPushLog($push_param,$push_data);

            }

        }

        try{

            $logArr['userId'] = (int)$param['userId'];
            $logArr['remark'] = '编辑应用白名单';
            
            $push_param['statusType'] = '编辑应用白名单';
            $push_param['title'] = 'OK';
            $push_param['batch'] = $pushArr;
            $push_param['status'] = 1;
            $push_param['contentType'] = 46;
            $push_param['userId'] = (int)$param['userId'];
            $push_data = ['package_name'=>$val];
            $jPush = LogUtil::addPushLog($push_param,$push_data);
            if(in_array(200,$jPush)){

                $data = [
                    'batch_id'=>$batch_id,
                    'sn'=>$sn,
                    'package_name'=>$val,
                    'update_time'=>time()
                ];

                if(DB::table('t_white_app')->where('id',$param['id'])->update($data)){
                    $logArr['details'] = '成功';
                    LogUtil::addAdminLog($logArr);
                    return ToolUtil::returnJson(200,'成功');
                }else{
                    $logArr['details'] = '失败';
                    LogUtil::addAdminLog($logArr);
                    return ToolUtil::returnJson(300,'失败');
                }

            }else{
                $logArr['details'] = '推送失败';
                LogUtil::addAdminLog($logArr);
                return ToolUtil::returnJson(300,'推送失败');
            }

        }catch (\Exception $exception){
            return ToolUtil::returnJson(500,'设置出错');
        }

    }


    /**
     * 删除应用白名单信息
     * @param $param
     * @return false|string
     */
    public static function whiteAppDelete($param){

        $white_app = DB::table('t_white_app')->where('id',$param['id'])->first(['batch_id','package_name','admin_id','sn','group']);
        if(empty($white_app)){
            return ToolUtil::returnJson(301,'不存在该信息');
        }
        if(!ToolUtil::isPower($param['userId'],$white_app['admin_id'])){
            return ToolUtil::returnJson(300,'没有权限');
        }

        if($white_app['group'] === 4){
            $push_param['type'] = 2;
            $pushArr = array($white_app['sn']);
        }else{
            $push_param['type'] = 1;
            $pushArr = explode(',',$white_app['batch_id']);
        }
    
        try{

            DB::beginTransaction();

            $logArr['userId'] = (int)$param['userId'];
            $logArr['remark'] = '删除应用白名单信息';
            $logArr['details'] = ToolUtil::handleSuccessOrError(['batch_id'=>$white_app['batch_id']]);
            LogUtil::addAdminLog($logArr);

            $push_param['statusType'] = '删除应用白名单信息';
            $push_param['title'] = 'OK';
            $push_param['batch'] = $pushArr;
            $push_param['status'] = 1;
            $push_param['contentType'] = 46;
            $push_param['userId'] = (int)$param['userId'];
            $push_data = ['package_name'=>''];
            $jPush = LogUtil::addPushLog($push_param,$push_data);

            if(in_array(200,$jPush)){
                if(DB::table('t_white_app')->where('id',$param['id'])->delete()){
                    DB::commit();
                    return ToolUtil::returnJson(200,'成功');
                }else{
                    return ToolUtil::returnJson(300,'失败');
                }         
            }else{
                return ToolUtil::returnJson(300,'推送失败');
            }

        }catch (\Exception $exception){
            DB::rollBack();
            return ToolUtil::returnJson(500,'设置出错');
        }

    }

    /**
     * 编号查询应用白名单
     * @param $param
     * @return false|string
     */
    public static function whiteAppById($param){
        $field = ['w.id','w.package_name','w.batch_id','w.sn','w.group'];
        $data = DB::table('t_white_app as w')->where('w.id',$param['id'])->first($field);
        if($data){
            $data['type'] = 1;
            return ToolUtil::returnJson(200,'成功',$data);
        }
        return ToolUtil::returnJson(400,'没有数据');
    }


    /**
     * 应用白名单列表
     * @param $param
     * @return false|string
     */
    public static function whiteAppList($param){

        $where = [];
        $admin = DB::table('t_admin')->where('id',$param['userId'])->value('id');
        if(empty($admin)){
            return ToolUtil::returnJson(301,'不存在该用户');
        }
        if(!ToolUtil::isAdmin($param['userId'])){
            $where[0] = " w.admin_id=$param[userId] ";
        }
        if(!empty($param['username'])){
            $where[count($where)+1] = " a.username like '%$param[username]%' ";
        }
        if(isset($param['batch']) && $param['batch'] != ''){
            $input_b = ToolUtil::filterStr($param['batch']);
            $batch_res = DB::table('t_batch')->where('name','like','%'.$input_b.'%')->get(['id']);

            $bidStr = '';
            foreach ($batch_res as $key => $value) {
                $bidStr .= $value['id'].",";
            }
            if($bidStr != ''){
                $bidStr = rtrim($bidStr,',');
                $where[count($where)+1] = " w.batch_id IN ({$bidStr}) ";
            }else{
                return ToolUtil::returnJson(400,'没有数据');
            }
        }
        $str = '';
        if($where){
            $str = ' where '.implode('and',$where);
        }
        $sort = " order by w.create_time desc ";
        $leftJoin = " left join t_admin as a on w.admin_id=a.id ";
        $count = DB::select("select count('*') as id from t_white_app as w $leftJoin $str");
        $limit = ToolUtil::calculationPageTwo($param,$count[0]['id']);
        $field = "w.id,a.username,w.sn,w.batch_id,w.batch_id as batch,w.package_name,w.create_time,w.update_time";
        $data = DB::select("select $field from t_white_app as w $leftJoin $str $sort $limit");
        if(count($data)){
            $data = ToolUtil::handleBatch($data,'batch');
            return ToolUtil::returnJson(200,'成功',$data,$count[0]['id']);
        }
        return ToolUtil::returnJson(400,'没有数据');

    }

}
